<template>
  <div id='CalcFormula'>
    <Breadcrumb content='核算公式' />
    <div class='bodyContent'>
      <el-tabs type='border-card'>
        <el-tab-pane label='核算公式'>
          <Splitpanes class='area'>
            <Pane size='55'>
              <vxe-toolbar perfect>
                <template #buttons>
                  <span class='smallToolTitle'>名称模糊查找:</span>
                  <vxe-input v-model='form.antName' placeholder='名称' class='vxeInputSearch' type='text' clearable @clear='findPageList'></vxe-input>
                  <vxe-button type='text' icon='vxe-icon-search' class='button-blue SearchBtn' content='查询' :loading='loading' @click='findPageList'></vxe-button>
                  <vxe-button type='text' class='button-blue' icon='vxe-icon-add' content='新增' @click='addBacGerm'></vxe-button>
                  <vxe-button type='text' icon='vxe-icon-delete' class='button-red' content='删除' @click='handleDelete'></vxe-button>
                </template>
              </vxe-toolbar>

              <div class='tableBox'>
                <vxe-table ref='antibioticsDictTable' border='inner' align='left' class='mytable-scrollbar' height='auto'
                           :data='antibioticsDictList'
                           :expand-config='{ expandAll: true, reserve: true }'
                           :row-config='{ isCurrent: true, isHover: true }'
                           :keyboard-config='{ isArrow: true, isTab: true, isEdit: true }'
                           :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }"
                           resizable show-overflow keep-source @current-change='roleRowClick'>
                  <vxe-column type='checkbox' width='30px'></vxe-column>
                  <vxe-column field='code' title='编码'></vxe-column>
                  <vxe-column field='itemName' title='核算表单'></vxe-column>
                  <vxe-column field='name' title='公式名称'></vxe-column>
                  <vxe-column field='isEnable' title='是否启用'>
                    <template #default='{ row }'>
                      <el-tag type='danger' v-if='row.isEnable === 0'>否</el-tag>
                      <el-tag type='success' v-else-if='row.isEnable === 1'>是</el-tag>
                      <span v-else>——</span>
                    </template>
                  </vxe-column>
                  <vxe-column field='remarks' title='备注描述'></vxe-column>
                  <vxe-column field='formulaTitle' title='计算公式'></vxe-column>
                </vxe-table>
              </div>
            </Pane>


            <Pane size='45'>
              <el-tabs type='border-card'>
                <el-tab-pane label='基本信息'>
                  <!-- 核算公式 基本信息表单-->
                  <CalcFormulaForm ref='refFormData' @getTableData='findPageList' />
                </el-tab-pane>
              </el-tabs>
            </Pane>
          </Splitpanes>
        </el-tab-pane>

        <el-tab-pane label='公式组合'>
          <Splitpanes class='area'>
            <Pane size='55'>
              <vxe-toolbar perfect>
                <template #buttons>
                  <span class='smallToolTitle'>名称模糊查找:</span>
                  <vxe-input v-model='groupForm.antName' placeholder='名称' class='vxeInputSearch' type='text' clearable @clear='findGroupList'></vxe-input>
                  <vxe-button type='text' icon='vxe-icon-search' class='button-blue SearchBtn' content='查询' :loading='loading' @click='findGroupList'></vxe-button>
                  <vxe-button type='text' class='button-blue' icon='vxe-icon-add' content='新增' @click='handAddGroup'></vxe-button>
                  <vxe-button type='text' icon='vxe-icon-delete' class='button-red' content='删除' @click='handleDeleteGroup'></vxe-button>
                </template>
              </vxe-toolbar>

              <div class='tableBox'>
                <vxe-table ref='groupTable' border='inner' align='left' class='mytable-scrollbar' height='auto'
                           :data='groupFormulaList'
                           :expand-config='{ expandAll: true, reserve: true }'
                           :row-config='{ isCurrent: true, isHover: true }'
                           :keyboard-config='{ isArrow: true, isTab: true, isEdit: true }'
                           :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }"
                           resizable show-overflow keep-source @current-change='groupRoleRowClick'>
                  <vxe-column type='checkbox' width='30px'></vxe-column>
                  <vxe-column field='code' title='编码'></vxe-column>
                  <vxe-column field='itemName' title='核算表单'></vxe-column>
                  <vxe-column field='groupName' title='公式名称'></vxe-column>
                  <vxe-column field='isEnable' title='是否启用'>
                    <template #default='{ row }'>
                      <el-tag type='danger' v-if='row.isEnable === 0'>否</el-tag>
                      <el-tag type='success' v-else-if='row.isEnable === 1'>是</el-tag>
                      <span v-else>——</span>
                    </template>
                  </vxe-column>
                  <vxe-column field='remarks' title='备注描述'></vxe-column>
                  <vxe-column field='formulaTitle' title='计算公式'></vxe-column>
                </vxe-table>
              </div>

            </Pane>


            <Pane size='45'>
              <el-tabs type='border-card'>
                <el-tab-pane label='基本信息'>
                  <!-- 核算公式 基本信息表单-->
                  <CalcFormulaGroupForm ref='refGroupFormData' @getTableData='findGroupList' />
                </el-tab-pane>
              </el-tabs>
            </Pane>
          </Splitpanes>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang='ts'>
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
import { Pane, Splitpanes } from 'splitpanes';
import { AppStore } from '@/stores/store';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import CalcFormulaForm from './CalcFormulaForm.vue';
import CalcFormulaGroupForm from './CalcFormulaGroupForm.vue';
import { format } from 'date-fns';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let form = reactive({
  antName: '' //名称
});

let antibioticsDictList: any = reactive([]); //核算公式列表

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];

let page = reactive({
  currentPage: 1,
  pageSize: 500,
  totalResult: 0
});

let loading = ref(false); //查询按钮加载

let saveLoading = ref(false);

let refFormData: any = ref(null); //信息表单ref
let refGroupFormData: any = ref(null); //信息表单ref

// 方法定义区 =============

/**
 * 页面加载时
 */
onMounted(() => {
  findPageList();
  findGroupList();
});

let addSeq = 0;

/**
 * 获取表格数据
 */
function findPageList() {
  loading.value = true;
  antibioticsDictList.length = 0;
  const url = '/wk/calc/formula/page';
  proxy.$http
    .get(url, {
      params: {
        searchValue: form.antName
      }
    })
    .then((res: any) => {
      antibioticsDictList.push(...res.data);
      addSeq = res.data.total + 1;
      refFormData.value.initAddPage(addSeq); //传递给右侧基本信息表单
      roleRowClick({
        row: antibioticsDictList[0],
        rowIndex: 0
      });
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('搜索核算公式列表异常', VxeNotifyType.error);
    });
}

/**
 * 新增按钮
 */
function addBacGerm() {
  const $formRef = refFormData.value;
  refFormData.value.addNew();
}

/**
 * 删除按钮
 */
function handleDelete() {
  const selectRows = (proxy.$refs.antibioticsDictTable as any).getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请勾选需要删除的数据', VxeNotifyType.warning);
    return;
  } else {
    proxy.$confirm('您确定要删除当前选中的这条数据吗?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const commaSeparatedIds = selectRows.map((row) => row.id);
      const ids = commaSeparatedIds.join(',');
      const data = { ids: ids };
      const url = '/wk/calc/formula/delete';
      proxy.$http.post(url, data).then((res: any) => {
        findPageList();
        refFormData.value.clearFormData(); //调用子组件的清空表单方法
        VxeMessage(res.status.msg, VxeNotifyType.success);
      }).catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
    });
  }
}

/**
 * 点击表格当前行
 * @param row
 * @param rowIndex
 */
function roleRowClick({ row, rowIndex }: any) {
  row.startDateStr = format(new Date(row.startDate), 'yyyy-MM-dd');
  row.endDateStr = format(new Date(row.endDate), 'yyyy-MM-dd');
  refFormData.value.initPage(row); //传递给右侧基本信息表单
  (proxy.$refs.antibioticsDictTable as any).setCurrentRow(row);
}


// ##############################################################################


let groupForm = reactive({
  antName: '' //名称
});

let groupFormulaList: any = reactive([]); //核算公式列表
function findGroupList() {
  groupFormulaList.length = 0;
  const url = '/wk-calc-formula-group/page';
  proxy.$http.get(url, { params: { searchValue: groupForm.antName } }).then((res: any) => {
    groupFormulaList.push(...res.data);
    refGroupFormData.value.initAddPage(); //传递给右侧基本信息表单
    groupRoleRowClick({
      row: groupFormulaList[0],
      rowIndex: 0
    });
  }).catch((err: any) => {
    VxeMessage('搜索核算公式列表异常', VxeNotifyType.error);
  });
}

function groupRoleRowClick({ row, rowIndex }: any) {
  row.startDateStr = format(new Date(row.startDate), 'yyyy-MM-dd');
  row.endDateStr = format(new Date(row.endDate), 'yyyy-MM-dd');
  console.log(row.startDate, '======>', row.startDateStr);
  console.log(row.endDate, '======>', row.endDateStr);
  refGroupFormData.value.initPage(row);
  (proxy.$refs.groupTable as any).setCurrentRow(row);
}

function handAddGroup() {
  refGroupFormData.value.addNew();
}

function handleDeleteGroup() {
  const selectRows = (proxy.$refs.groupTable as any).getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请勾选需要删除的数据', VxeNotifyType.warning);
    return;
  } else {
    proxy.$confirm('您确定要删除当前选中的这条数据吗?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const commaSeparatedIds = selectRows.map((row) => row.id);
      const ids = commaSeparatedIds.join(',');
      const data = { ids: ids };
      const url = '/wk-calc-formula-group/delete';
      proxy.$http.post(url, data).then((res: any) => {
        findGroupList();
        refGroupFormData.value.clearFormData(); //调用子组件的清空表单方法
        VxeMessage(res.status.msg, VxeNotifyType.success);
      }).catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
    });
  }
}

</script>

<style lang='scss' scoped>
#CalcFormula {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .el-tabs {
      height: 100%;

      :deep(.el-tabs__content) {
        height: calc(100% - 39px);
        padding: 0px;

        .el-tab-pane {
          height: 100%;
        }
      }
    }

    .area {
      background-color: $base-white;
    }

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 查询按钮
    .SearchBtn {
      margin-right: 5px;
    }

    .tableBox {
      height: calc(100% - 40px);

      .vxe-table {
        height: 100%;

        :deep(.vxe-table--render-wrapper) {
          height: 100%;

          .vxe-table--main-wrapper {
            height: 100%;

            .vxe-table--body-wrapper {
              height: calc(100% - 26px) !important;
            }
          }
        }
      }
    }
  }
}
</style>

